package com.coocaa.x.demo.servlets;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.service.litewebserver.webserver.NanoHTTPD;
import com.coocaa.x.service.litewebserver.webserver.servlet.Servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * Created by lu on 15-9-11.
 */
public class CacheServlet extends Servlet {
    private ServletInfo info = null;

    @Override
    protected void onCreate() {

    }

    @Override
    protected void onDestroy() {

    }

    @Override
    protected NanoHTTPD.Response onServe(NanoHTTPD.IHTTPSession session) {
        String uri = session.getUri();
        String cache = uri.substring("/cache".length());
        File f = new File(CoocaaApplication.getContext().getCacheDir().getAbsolutePath() + "/" + cache);
        try {
            InputStream is = new FileInputStream(f);
            return newChunkedResponse(NanoHTTPD.Response.Status.OK, NanoHTTPD.MIME_IMAGEJPEG, is);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return newFixedLengthResponse(NanoHTTPD.Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "not found");
    }

    @Override
    public synchronized ServletInfo getServletInfo() {
        if (info == null) {
            info = new ServletInfo();
            info.vendorName = "superx";
            info.servletName = "cache";
            info.versionCode = 1;
            info.versionName = "1.0.0";
        }
        return info;
    }

    @Override
    protected InputStream getResource(String uri) {
        return null;
    }
}
